﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WomanMotion.WebApi.Infrastructure.Common;
using WomanMotion.WebApi.Infrastructure.DataBaseCommon;
using WomanMotion.WebApi.Model.Dtos.Match;
using WomanMotion.WebApi.Model.Dtos.SendMessage;
using WomanMotion.WebApi.Model.Dtos.Team;
using WomanMotion.WebApi.Model.Entitys;
using WomanMotion.WebApi.Repository.IRepository;
using WomanMotion.WebApi.Service.IService;
using WomanMotion.WebApi.Wechat.IService;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.ComponentTCBBatchDeleteContainerServiceVersionRequest.Types;

namespace WomanMotion.WebApi.Service.Service
{
    public class SendMessageService : BaseCRUDService<SendMessage, SendMessageVM, UpdateSendMessageDTO, CreatedSendMessageDTO>, ISendMessageService
    {
        private readonly ISendMessageRepository _sendMessageRepository;
        private readonly IUsersService _usersService;
        private readonly IMatchService _matchService;
        private readonly IConfiguration _configuration;
        private readonly IWechatCommon _wechatCommon;

        public SendMessageService(ILogger<SendMessageService> logger, IMapper mapper, ISendMessageRepository sendMessageRepository, IHttpContextAccessor _httpContext, IUsersService usersService, IMatchService matchService, IConfiguration configuration, IWechatCommon wechatCommon) : base(logger, mapper, sendMessageRepository, _httpContext)
        {
            _sendMessageRepository = sendMessageRepository;
            _usersService = usersService;
            _matchService = matchService;
            _configuration = configuration;
            _wechatCommon = wechatCommon;
        }

        /// <summary>
        /// 定时发送订阅消息
        /// </summary>
        /// <returns></returns>
        public async Task SendMsg()
        {
            // 获取当前时间
            DateTime now = DateTime.Now;

            // 计算当前时间减去5分钟后的时间
            DateTime minus6mins = now.AddMinutes(-6);

            // 计算当前时间加上5分钟后的时间
            DateTime plus6mins = now.AddMinutes(6);
            //查询符合数据的订阅信息
            var matchdata = await this.GetListAsync(m => m.Issend == 0 && m.Matchtime >= minus6mins && m.Matchtime <= plus6mins);
            List<SendData> sends = new List<SendData>();
            foreach (var item in matchdata)
            {
                //查询是否有openid
                var user = await _usersService.GetEntityAsync(m => m.Id == item.Userid);
                if (user != null && user.Wxid != null && user.Wxid != "")
                {
                    var send = new SendData();
                    send.id = item.Id;
                    send.openid = user.Wxid;
                    send.matchtime = item.Matchtime.ToString("yyyy-MM-dd HH:mm:ss");
                    //获取比赛
                    var match = await _matchService.GetByIDNavAsync(item.Matchid);
                    send.classname = match.Classify.Name;
                    send.teamname = match.Teama.Name + " VS " + match.Teamb.Name;
                    send.watchname = match.Watch.Name;
                    sends.Add(send);
                }
            }
            var tokenModel = _configuration.GetSection("SendMegTemp").Get<SendMegTemp>();
            foreach (var item in sends)
            {
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("thing3", item.classname);
                data.Add("thing2", item.matchtime);
                data.Add("thing6", item.teamname);
                data.Add("thing10", item.watchname);
                _logger.LogInformation("开始推送");
                var res = await _wechatCommon.MatchSendMegAsync(item.openid, tokenModel.templateid, data);
                _logger.LogInformation(res.Key.ToString());
                _logger.LogInformation(res.Value);
                _logger.LogInformation("完成推送");
                var test = await this.GetEntityAsync(m => m.Id == item.id);
                _logger.LogInformation("获取推送实体");
                _logger.LogInformation(JsonConvert.SerializeObject(test));
                test.Issend = 1;
                await this.UpdateEntityAsync(test);
                _logger.LogInformation("更新实体");
                _logger.LogInformation(JsonConvert.SerializeObject(test));
            }
            _logger.LogInformation("定时任务执行了");
        }
    }
}